package com.uni.controllers;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.uni.controllers.validation.LectionValidator;
import com.uni.db.GenericService;
import com.uni.domain.Course;
import com.uni.domain.File;
import com.uni.domain.Lection;
import com.uni.utils.FileUtils;

@Controller
@RequestMapping("/lectionEdit.htm")
@SessionAttributes(types = Lection.class)
public class LectionEdit {

    @Autowired
	@Qualifier("lectionService")
	private GenericService<Lection> lectionService;

    @Autowired
	@Qualifier("courseService")
	private GenericService<Course> courseService;

    @Autowired
	@Qualifier("fileService")
	private GenericService<File> fileService;

    @RequestMapping(method = RequestMethod.GET)
	public String setupForm(
							@RequestParam(value="id", required=false) Integer id,
                         	@RequestParam(value="course", required=true) Long idc, 
                         	ModelMap model, 
                         	HttpSession session
                         	) {
    	if(idc == null){
			model.addAttribute("message", "��� id �����? �??????");
			return "error";
		}
    	Course course = courseService.get(idc);
    	if(course == null){
			model.addAttribute("message", "���� �� ������");
			return "error";
		}
    	session.setAttribute("course", course);
    	Lection lection;
		if (id == null){
			lection = new Lection();
		} else {
			lection = course.getLection(id);
			if(lection == null){
				model.addAttribute("message", "������ �� �������");
				return "error";
			}
		}
		model.addAttribute("lection", lection);
		model.addAttribute("course", course);
		System.out.println("lectionEdit");
        return "lectionEdit";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute Lection lection, 
								BindingResult result,
								SessionStatus status,
								HttpSession session,
								HttpServletRequest req) {
		new LectionValidator().validate(lection, result);
		if (result.hasErrors()) {
			return "lectionEdit";
		} else {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest)req;
            Course course = (Course)session.getAttribute("course");
            session.removeAttribute("course");
            if(lection.isNew()){
            	course.addLection(lection);
            	courseService.save(course);
            } else {
	            clearFiles(lection, req);
            }
			parseFiles(lection, request);
            lectionService.save(lection);
            status.setComplete();
            return "redirect:/course/" + course.getId();
        }
	}
	
	private void parseFiles(Lection lection, MultipartHttpServletRequest request){
		List<File> presentation = lection.getPresentationFiles();
		List<File> question = lection.getQuestionFiles();
		List<File> other = lection.getOtherFiles();
		Iterator<String> i = request.getFileNames();
		while(i.hasNext()){
			String name = i.next();
			MultipartFile mfile = request.getFile(name);
			File file = FileUtils.parseFile(mfile, "", fileService);
			if(file == null) continue;
			if(name.startsWith("presentation")){
				file.setType("presentation");
				presentation.add(file);
			} else if(name.startsWith("question")){
				file.setType("question");
				question.add(file);
			} else if(name.startsWith("other")){
				file.setType("other");
				other.add(file);
			}
		}
		lection.setPresentationFiles(presentation);
		lection.setQuestionFiles(question);
		lection.setOtherFiles(other);
	}
	
	private void clearFiles(Lection lection, HttpServletRequest request){
		String[] pNames = request.getParameterValues("presentation[]");
		String[] qNames = request.getParameterValues("question[]");
		String[] oNames = request.getParameterValues("other[]");
		clearFile(lection.getPresentationFiles(), pNames);
		clearFile(lection.getQuestionFiles(), qNames);
		clearFile(lection.getOtherFiles(), oNames);
	}
	
	private void clearFile(List<File> files, String[] names){
		if(names == null) {
			files.clear();
			return;
		}
		
		for(File f : files){
			System.out.println(f.getFileName() + " => " + f.getId());
		}
		System.out.println("----");
		for(String s : names){
			System.out.println(s);
		}
		
		for(int i = 0 ; i < files.size() ; i ++){
			boolean find = false;
			File f = files.get(i);
			String id = f.getId().toString();
			for(String name : names){
				if(id.equals(name)){
					find = true;
					continue;
				}
			}
			if(!find){
				fileService.delete(f);
				files.remove(f);
				i--;
			}
		}
	}
}





